package com.bitejiuyeke.job_publish.service.impl;

import com.bitejiuyeke.job_publish.common.AppResult;
import com.bitejiuyeke.job_publish.common.PageResult;
import com.bitejiuyeke.job_publish.common.ResultCode;
import com.bitejiuyeke.job_publish.dao.UserMapper;
import com.bitejiuyeke.job_publish.enums.*;
import com.bitejiuyeke.job_publish.exception.ApplicationException;
import com.bitejiuyeke.job_publish.model.Major;
import com.bitejiuyeke.job_publish.model.User;
import com.bitejiuyeke.job_publish.service.IMajorService;
import com.bitejiuyeke.job_publish.service.IUserService;
import com.bitejiuyeke.job_publish.utils.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @Author 比特就业课
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    // 有效时间 60 分钟
    private static final int EFFECTIVE_TIME = 60 * 60;

    private static final String KEY_CODE_PREFIX = "KEY_USER:ID:";
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private FileUtils fileUtils;
    @Resource
    private UserMapper mapper;
    @Resource
    private IMajorService majorService;

    @Override
    public void create(User user) {
        // 参数校验
        if (user == null || StringUtils.isEmpty(user.getName())
                || StringUtils.isEmpty(user.getPhoneNum())
                || StringUtils.isEmpty(user.getPassword())) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询电话号码是否存在
        User existUser = selectByPhoneNum(user.getPhoneNum());
        if (existUser != null) {
            log.info(ResultCode.FAILED_PHONE_EXISTS.toString() + "phone num = " + user.getPhoneNum());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PHONE_EXISTS));
        }
        // 设置用户默认值
        // 性别
        if (user.getGender() == null || user.getGender() < 0 || user.getGender() > 2) {
            user.setGender((byte) 2);
        }
        // 设置盐和密码密文
        String salt = UUIDUtils.UUID_32();
        String encryptPwd = MD5Utils.md5Salt(user.getPassword(), salt);
        user.setPassword(encryptPwd); // 密文
        user.setSalt(salt); // 盐
        // 隐私状态
        user.setPrivacyState((byte) PrivacyStateEnum.PRIVATE.getCode());
        // 已投递数
        user.setSendCount(0);
        // 收藏数
        user.setFavoriteCount(0);
        // 用户状态
        user.setState((byte) StateEnum.NORMAL.getCode());
        // 是否删除
        user.setDeleteState((byte) DeleteStateEnum.NORMAL.getCode());
        // 创建和更新时间
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);
        // 写入数据库
        int row = mapper.insertSelective(user);
        if (row != 1) {
            // 记录日志
            log.info("新增用户失败" + user.getPhoneNum());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 记录日志
        log.info("新增用户成功" + user.getPhoneNum());
    }

    @Override
    public User selectById(Long id) {
        // 参数校验
        if (id == null || id <= 0) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 先从缓存中获取用户信息
        User user = getFromCache(id);
        if (user != null) {
            // 缓存中存在直接返回
            return user;
        }
        // 缓存中不存在从数据库中查询
        user = mapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == DeleteStateEnum.DELETED.getCode()) {
            // 数据库中也为null直接返回
            return null;
        }
        // 查询院系信息
        Major major = majorService.selectDetailsById(user.getMajorId());
        user.setMajor(major);
        // 把用户信息设置到缓存
        setToCache(user);
        // 返回用户信息
        return user;
    }


    @Override
    public User selectByPhoneNum(String phoneNum) {
        // 参数校验
        if (StringUtils.isEmpty(phoneNum)) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 从数据库中查询
        User user = mapper.selectByPhoneNum(phoneNum);
        return user;
    }

    @Override
    public User selectByEmail(String email) {
        // 参数校验
        if (StringUtils.isEmpty(email)) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 从数据库中查询
        User user = mapper.selectByEmail(email);
        return user;
    }

    @Override
    public User selectByName(String name) {
        // 参数校验
        if (StringUtils.isEmpty(name)) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 从数据库中查询
        User user = mapper.selectByName(name);
        return user;
    }

    @Override
    public User loginByPhoneNum(String phoneNum, String password) {
        // 校验
        if (StringUtils.isEmpty(phoneNum) || StringUtils.isEmpty(password)) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 根据电话号码查询用户
        User user = mapper.selectByPhoneNum(phoneNum);
        if (user == null) {
            log.info(ResultCode.FAILED_PHONE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PHONE_NOT_EXISTS));
        }

        // 校验密码
        boolean bool = checkLogin(user, password);
        if (!bool) {
            log.info(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 查询院系信息
        Major major = majorService.selectDetailsById(user.getMajorId());
        user.setMajor(major);
        // 登录成功，写入缓存
        setToCache(user);
        return user;
    }

    @Override
    public User loginByEmail(String email, String password) {
        // 校验
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 根据电子邮箱查询用户
        User user = mapper.selectByEmail(email);
        if (user == null) {
            log.info(ResultCode.FAILED_EMAIL_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_EMAIL_NOT_EXISTS));
        }

        // 校验密码
        boolean bool = checkLogin(user, password);
        if (!bool) {
            log.info(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 查询院系信息
        Major major = majorService.selectDetailsById(user.getMajorId());
        user.setMajor(major);
        // 登录成功，写入缓存
        setToCache(user);
        return user;
    }

    // 校验密码
    private boolean checkLogin (User user, String password) {
        // 用户输入的密码加盐
        String encryptPwd = MD5Utils.md5Salt(password, user.getSalt());
        // 校验
        if (encryptPwd.equalsIgnoreCase(user.getPassword())) {
            // 校验通过
            return true;
        }
        // 校验不通过
        return false;
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        // 校验
        if (id == null || StringUtils.isEmpty(newPassword) || StringUtils.isEmpty(oldPassword)) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 先清空缓存中的数据
        redisUtils.del(buildKey(id));
        // 查询用户
        User user = selectById(id);
        // 用户不存在
        if (user == null) {
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 校验原密码是否正确
        String oldEncryptPwd = MD5Utils.md5Salt(oldPassword, user.getSalt());
        if (!oldEncryptPwd.equalsIgnoreCase(user.getPassword())) {
            // 原密码不正确
            log.info("原密码不正确, user id = " + user.getId());
            throw new ApplicationException(AppResult.failed("原密码不正确"));
        }
        // 生成新的密码和盐
        String salt = UUIDUtils.UUID_32();
        String encryptPwd = MD5Utils.md5Salt(newPassword, salt);
        // 创建更新用户
        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户Id
        updateUser.setSalt(salt); // 盐
        updateUser.setPassword(encryptPwd); // 新密码
        updateUser.setUpdateTime(new Date()); // 日期

        // 更新数据
        int row = mapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.info("修改密码失败. user id = " + user.getId());
            throw new ApplicationException(AppResult.failed("修改密码失败."));
        }
        log.info("修改密码成功. user id = " + user.getId());
    }

    @Override
    public void modifyInfo(User user) {
        // 校验
        if (user == null || user.getId() == null || user.getId() <= 0) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 定义用来更新的对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        // 校验基本信息
        boolean checkResult = checkUserBaseInfo(user, updateUser);
        // 基本信息全部为空时校验不通过
        if (!checkResult) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 更新时间
        updateUser.setUpdateTime(new Date());
        // 更新用户信息
        int row = mapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.info("更新用户信息失败. user id = " + user.getId());
            throw new ApplicationException(AppResult.failed("更新用户信息失败."));
        }
        // 删除缓存
        redisUtils.del(buildKey(user.getId()));

    }

    // 校验用户基本信息
    private boolean checkUserBaseInfo(User user, User updateUser) {
        // 分别校验：院系、姓名、学号、性别、入学时间、身份、标签、隐私状态、个人简介
        boolean checkFlag = false;
        // 院系
        if (user.getMajorId() != null && user.getMajorId() > 0) {
            updateUser.setMajorId(user.getMajorId());
            checkFlag = true;
        }
        // 姓名
        if (!StringUtils.isEmpty(user.getName())) {
            updateUser.setName(user.getName());
            checkFlag = true;
        }
        // 学号
        if (!StringUtils.isEmpty(user.getSNo())) {
            updateUser.setSNo(user.getSNo());
            checkFlag = true;
        }
        // 性别
        if (user.getGender() != null && GenderStateEnum.valueOf(user.getGender()) != null) {
            updateUser.setGender(user.getGender());
            checkFlag = true;
        }
        // 入学时间
        if (user.getEnrollment() != null) {
            updateUser.setEnrollment(user.getEnrollment());
            checkFlag = true;
        }
        // 标签
        if (!StringUtils.isEmpty(user.getTag())) {
            updateUser.setTag(user.getTag());
            checkFlag = true;
        }
        // 个人简介
        if (!StringUtils.isEmpty(user.getRemark())) {
            updateUser.setRemark(user.getRemark());
            checkFlag = true;
        }
        // 状态
        if (user.getState() != null) {
            updateUser.setState(user.getState());
            checkFlag = true;
        }
        // 返回校验结果
        return checkFlag;
    }

    @Override
    public void modifyPrivateState(Long userId, Byte privateState) {
        // 校验
        PrivacyStateEnum privacyStateEnum = PrivacyStateEnum.valueOf(privateState);
        if (userId == null || privateState == null || userId <= 0
                || privacyStateEnum == null) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询用户
        User user = selectById(userId);
        if (user == null) {
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 更新对象
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setPrivacyState((byte) privacyStateEnum.getCode());
        updateUser.setUpdateTime(new Date());
        // 公开时需要校验
        if (privacyStateEnum == PrivacyStateEnum.PUBLIC) {
            checkUserPrivateState(user);
        }
        // 更新用户信息
        int row = mapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.info("更新用户状态失败. user id = " + user.getId());
            throw new ApplicationException(AppResult.failed("更新用户状态失败."));
        }
        // 删除缓存
        redisUtils.del(buildKey(user.getId()));

    }

    // 更新用户状态时校验基本信息是否完整
    private void checkUserPrivateState(User user) {
        if (user == null) {
            throw new ApplicationException(AppResult.failed("没有对应的用户."));
        }
        // 姓名
        if (StringUtils.isEmpty(user.getName())) {
            throw new ApplicationException(AppResult.failed("请填写姓名."));
        }
        // 学号
        if (StringUtils.isEmpty(user.getSNo())) {
            throw new ApplicationException(AppResult.failed("请填写学号."));
        }
        // 专业
        if (user.getMajorId() == null) {
            throw new ApplicationException(AppResult.failed("请填写专业."));
        }
        // 入学时间
        if (user.getEnrollment() == null) {
            throw new ApplicationException(AppResult.failed("请填写入学时间."));
        }
        // 电话号码
        if (StringUtils.isEmpty(user.getPhoneNum()) && StringUtils.isEmpty(user.getEmail())) {
            throw new ApplicationException(AppResult.failed("请填写电话号码或电子邮箱."));
        }
        // 头像
        if (StringUtils.isEmpty(user.getAvatarUrl())) {
            throw new ApplicationException(AppResult.failed("请上传头像."));
        }
        // 简历
        if (StringUtils.isEmpty(user.getResumeUrl())) {
            throw new ApplicationException(AppResult.failed("请上传简历."));
        }
        // 技能标签
        if (StringUtils.isEmpty(user.getTag())) {
            throw new ApplicationException(AppResult.failed("请填写技能标签."));
        }
        // 个人简介
        if (StringUtils.isEmpty(user.getRemark())) {
            throw new ApplicationException(AppResult.failed("请填写个人简介."));
        }
    }

    @Override
    public void modifyPhoneNum(Long id, String phoneNum, String verificationCode) {

    }

    @Override
    public void modifyEmail(Long id, String email, String verificationCode) {

    }

    @Override
    public User uploadAvatar(Long id, MultipartFile avatar) {
        // 校验
        if (id == null || avatar == null) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询用户信息
        User user = selectById(id);
        if (user == null) {
            log.info(ResultCode.FAILED_USER_NOT_EXISTS + " id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 写入磁盘
        String filePath;
        try {
            filePath = fileUtils.saveFile(avatar, UploadFileTypeEnum.PIC);
        } catch (IOException e) {
            log.error(ResultCode.FAILED_UPLOAD.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UPLOAD));
        }
        // 更新用户信息
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setAvatarUrl(filePath);
        updateUser.setUpdateTime(new Date());
        int row = mapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.info("上传用户头像失败. user id = " + user.getId());
            throw new ApplicationException(AppResult.failed("上传用户头像失败."));
        }
        // 删除缓存
        redisUtils.del(buildKey(user.getId()));
        // 重新获取用户
        user = selectById(user.getId());
        // 返回用户信息
        return user;
    }

    @Override
    public User deleteAvatar(Long id) {
        // 校验
        if (id == null) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询用户信息
        User user = selectById(id);
        if (user == null) {
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString() + " id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 更新用户信息
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setAvatarUrl("");
        updateUser.setUpdateTime(new Date());
        int row = mapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.info("删除用户头像失败. user id = " + user.getId());
            throw new ApplicationException(AppResult.failed("删除用户头像失败."));
        }
        // 删除缓存
        redisUtils.del(buildKey(user.getId()));
        // 重新获取用户
        user = selectById(user.getId());
        // 返回用户信息
        return user;
    }

    @Override
    public User uploadResume(Long id, MultipartFile resume) {
        // 校验
        if (id == null || resume == null) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询用户信息
        User user = selectById(id);
        if (user == null) {
            log.info(ResultCode.FAILED_USER_NOT_EXISTS + " id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 写入磁盘
        String filePath;
        try {
            filePath = fileUtils.saveFile(resume, UploadFileTypeEnum.FILE);
        } catch (IOException e) {
            log.error(ResultCode.FAILED_UPLOAD.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UPLOAD));
        }
        // 更新用户信息
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setResumeUrl(filePath);
        updateUser.setUpdateTime(new Date());
        int row = mapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.info("上传用户简历失败. user id = " + user.getId());
            throw new ApplicationException(AppResult.failed("上传用户简历失败."));
        }
        // 删除缓存
        redisUtils.del(buildKey(user.getId()));
        // 重新获取用户
        user = selectById(user.getId());
        // 返回用户信息
        return user;
    }

    @Override
    public User deleteResume(Long id) {
        // 校验
        if (id == null) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询用户信息
        User user = selectById(id);
        if (user == null) {
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString() + " id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 更新用户信息
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setResumeUrl("");
        // 删除简历同时设置为私密
        updateUser.setPrivacyState((byte) PrivacyStateEnum.PRIVATE.getCode());
        updateUser.setUpdateTime(new Date());
        int row = mapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.info("删除用户简历失败. user id = " + user.getId());
            throw new ApplicationException(AppResult.failed("删除用户简历失败."));
        }
        // 删除缓存
        redisUtils.del(buildKey(user.getId()));
        // 重新获取用户
        user = selectById(user.getId());
        // 返回用户信息
        return user;
    }

    @Override
    public void addFavoriteCount(Long id, Integer count) {
        if (id == null || id <= 0 || count == null || count <= 0) {
            log.info("增加用户收藏数失败. " + ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取User对象
        User user = selectById(id);
        if (user == null) {
            log.info("增加用户收藏数失败. " + ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 构建更新对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        int favoriteCount = user.getFavoriteCount() + count;
        updateUser.setFavoriteCount(favoriteCount);
        updateUser.setUpdateTime(new Date());
        // 更新数据库
        int row = mapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.info("增加用户收藏数失败. " + ResultCode.FAILED);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        // 更新缓存
        user.setFavoriteCount(favoriteCount);
        setToCache(user);
    }

    @Override
    public void minusFavoriteCount(Long id, Integer count) {
        if (id == null || id <= 0 || count == null || count <= 0) {
            log.info("减少用户收藏数失败. " + ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取User对象
        User user = selectById(id);
        if (user == null) {
            log.info("减少用户收藏数失败. " + ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 构建更新对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        int favoriteCount = user.getFavoriteCount() - count < 0 ? 0 : user.getFavoriteCount() - count;
        updateUser.setFavoriteCount(favoriteCount);
        updateUser.setUpdateTime(new Date());

        // 更新数据库
        int row = mapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.info("增加用户收藏数失败. " + ResultCode.FAILED);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        // 更新缓存
        user.setFavoriteCount(favoriteCount);
        setToCache(user);
    }

    @Override
    public void addSendCount(Long id, Integer count) {
        if (id == null || id <= 0 || count == null || count <= 0) {
            log.info("增加用户投递数失败. " + ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取User对象
        User user = selectById(id);
        if (user == null) {
            log.info("增加用户投递数失败. " + ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 构建更新对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        int sendCount = user.getSendCount() + count;
        updateUser.setSendCount(sendCount);
        // 更新数据库
        int row = mapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.info("增加用户投递数失败. " + ResultCode.FAILED);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        // 更新缓存
        user.setSendCount(sendCount);
        setToCache(user);
    }

    @Override
    public int totalCount(User record) {
        if (record == null || record.getPageSize() == null || record.getOffset() == null) {
            log.info("获取用户记录总数失败. " + ResultCode.FAILED_PARAMS_VALIDATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询总记录数
        int totalCount = mapper.totalCount(record);
        return totalCount;
    }

    @Override
    public PageResult<User> selectByPage(User record) {
        // 获取总记录数
        int totalCount = totalCount(record);
        // 返回结果
        PageResult<User> pageResult = new PageResult<>(record.getPageNum(), record.getPageSize(), totalCount);
        // 查询分页数据
        List<User> list = mapper.selectByPage(record);
        pageResult.setRows(list);
        return pageResult;
    }

    // 构造KEY
    private String buildKey(Long id) {
        return KEY_CODE_PREFIX + id;
    }

    // 从缓存中获取数据
    private User getFromCache(Long id) {
        // 获取缓存中的数据
        String content = (String) redisUtils.get(buildKey(id));
        if (StringUtils.isEmpty(content)) {
            // 缓存中不存在
            return null;
        }
        // 缓存中存在直接返回
        User user = JsonUtils.readValue(content, User.class);
        return user;
    }

    // 向缓存中设置数据
    private void setToCache(User user) {
        if (user == null || user.getId() == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        String jsonStr = JsonUtils.writeValueAsString(user);
        redisUtils.set(buildKey(user.getId()), jsonStr, EFFECTIVE_TIME);
    }


}
